package school.xauat.古典密码学;

/**
 * @author ：zsy
 * @date ：Created 2021/6/16 23:36
 * @description：凯撒加密
 */
public class KaiserDemo {
    public static void main(String[] args) {
        String encryptData = encrypt("Hello World", 3);
        System.out.println("加密后：" + encryptData);
        String decryptDate = decrypt(encryptData, 3);
        System.out.println("解密后：" + decryptDate);
    }

    public static String encrypt(String orignal, int key) {
        StringBuilder builder = new StringBuilder();
        char[] chars = orignal.toCharArray();
        for (char c : chars) {
            //转换为ascii码值
            int asciiCode = c;
            //偏移数据
            asciiCode += key;
            //转换回编码
            char newChar = (char)asciiCode;
            builder.append(newChar);
        }
        return builder.toString();
    }

    public static String decrypt(String encryptData, int key) {
        StringBuilder builder = new StringBuilder();
        char[] chars = encryptData.toCharArray();
        for (char c : chars) {
            //转换为ascii码值
            int asciiCode = c;
            //偏移数据
            asciiCode -= key;
            //转换回编码
            char newChar = (char)asciiCode;
            builder.append(newChar);
        }
        return builder.toString();
    }
}
